from app.service.driver import Driver
from app.lib.AliDNS import AliDNS
from app.functions import *
from app.config import SysConfig


class Ali(Driver):
    def __init__(self, secret_id, secret_key, domain=""):
        self.DomainName = domain
        self.dnsPod = AliDNS({
            'secretId': secret_id,
            'secretKey': secret_key
        })

    def addRecord(self, subDomain, recordValue):
        return self.RecordCreate(subDomain, recordValue, 'TXT')

    def cleanRecord(self, subDomain):
        res = self.RecordList(subDomain, 'TXT')
        if res.get('status') != SysConfig.STATUS_CODE_SUCCESS:
            return res
        records = res.get('data', {}).get('RecordList', [])
        for record in records:
            delRes = self.dnsPod.DeleteRecord(self.DomainName, record["RecordId"])
            if delRes.get('status') != SysConfig.STATUS_CODE_SUCCESS:
                return delRes
        return funReturn(SysConfig.STATUS_CODE_SUCCESS, 'success')

    def RecordCreate(self, subDomain, recordValue, recordType):
        queryRes = self.dnsPod.DescribeRecordList(self.DomainName, {"subDomain": subDomain, "recordType": recordType})
        status = queryRes.get('status')
        if status == SysConfig.STATUS_CODE_SUCCESS:
            listData = queryRes.get('DomainRecords', {}).get('Record', {})
            if listData:
                for record in listData:
                    if record.get('RR') == subDomain:
                        self.dnsPod.DeleteRecord(self.DomainName, record['RecordId'])
                        break
        return self.dnsPod.CreateRecord(self.DomainName, subDomain, recordType, recordValue)

    def RecordList(self, subDomain, recordType=''):
        res = self.dnsPod.DescribeRecordList(self.DomainName, {"subDomain": subDomain, "recordType": recordType})
        if res.get('status') != SysConfig.STATUS_CODE_SUCCESS:
            return res
        listData = res.get('data', {}).get('DomainRecords', {}).get('Record', [])
        returnData = [record for record in listData if record["RR"] == subDomain]
        return funReturn(SysConfig.STATUS_CODE_SUCCESS, 'success', {"RecordList": returnData})
